#include "include/gtest.h"
#include "../Tool/include/ILogger.h"
#include "../Tool/include/TcpServer.h"
#include <thread>
#include "../Tool/include/Variant.h"

using namespace Tool;

class ServerListener : public ITcpListener
{
public:
    TcpServer* server;

    ServerListener() : server(new TcpServer(this, 10)) {}
    ~ServerListener() { delete server; }

    void OnConnect(const char* pAddress, uint16_t nPort) override
    {
        // LOG_INFO("[Server] 客户端连接: %s:%d", pAddress, nPort);
    }

    void OnDisconnect(const char* pAddress, uint16_t nPort) override
    {
        LOG_INFO("[Server] 客户端断开: %s:%d", pAddress, nPort);
    }

    void OnReceive(const char* pAddress, uint16_t nPort, const void* pBuffer, size_t nLength) override
    {
        std::vector<uint8_t> binaryStr(static_cast<const uint8_t*>(pBuffer),static_cast<const uint8_t*>(pBuffer) + nLength);
        Variant variant;
        variant.FromBinaryString(binaryStr);

        LOG_INFO("[Server] 收到数据: (%s:%d) :%s", pAddress, nPort, variant.ToJsonString().c_str());

        variant["code"] = 200;
        const std::vector<uint8_t>& reply = variant.ToBinaryString();
        server->Send(pAddress, nPort, reply.data(), reply.size());
    }

    void OnNotify(const char* pAddress, uint16_t nPort, const char* pMsg) override
    {
        LOG_INFO("[Server] 通知: (%s:%d) :%s", pAddress, nPort, pMsg);
    }
};

TEST(TcpServer, TcpServerInteraction)
{
    std::thread server_thread([](){
        ServerListener serverListener;
        serverListener.server->Start("", 5090);
        while (true)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(5000));
        }
        serverListener.server->Stop();
    });
    server_thread.join();
}
